package com.example.demo.service.serviceImpl;

import com.example.demo.pojo.Page;
import com.example.demo.pojo.Transaction;
import com.example.demo.repository.TransactionRepository;
import com.example.demo.repository.repositoryImpl.UserRepositoryImpl;
import com.example.demo.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TransactionServiceImpl implements TransactionService {
    private final Integer CURRENT_COUNT = 1;

    @Autowired
    private TransactionRepository transactionRepository;

    @Autowired
    private UserRepositoryImpl userRepository;

    @Override
    public boolean addTrans(Transaction transaction) {

        transaction.setT_time(new Date());
        Transaction save = transactionRepository.save(transaction);
        return save != null;
    }

    @Override
    public Page transAllList(int currentPage) {


        Page page = new Page();
        Integer num = transactionRepository.countAll();
        int start = (currentPage - 1) * CURRENT_COUNT;
        int listNum = CURRENT_COUNT;
        List<Transaction> transactionList = transactionRepository.findAll(start, listNum);
        int totalPage = (int)Math.ceil(num * 1.0 / CURRENT_COUNT);
        page.setTotalCount(num);
        page.setTotalPage(totalPage);
        page.setCurrentCount(listNum);
        page.setCurrentPage(currentPage);
        page.setListForObject(transactionList);
        return page;
    }

    @Override
    public Page transUserList(Integer u_id, int currentPage) {


        Page page = new Page();
        Integer num = transactionRepository.countAllByUserId(u_id);
        int start = (currentPage - 1) * CURRENT_COUNT;
        int listNum = CURRENT_COUNT;
        List<Transaction> transactionList = transactionRepository.findByUserId(u_id, start, listNum);
        int totalPage = (int)Math.ceil(num * 1.0 / CURRENT_COUNT);
        page.setTotalCount(num);
        page.setTotalPage(totalPage);
        page.setCurrentCount(listNum);
        page.setCurrentPage(currentPage);
        page.setListForObject(transactionList);
        return page;
    }

}
